package day0215;

public class BinarySearch {


    /**
     * 对一个已经升序排序好的数组进行二分查找
     * @param arr 数组
     * @param num 查找的数
     * @return 下标。如果数组中不包含则返回 -1
     */
    static int binarySearch(int[] arr, int num) {
        int left = 0;
        int right = arr.length - 1;

        while(left <= right) {
            int middle = (left + right) / 2;
            if (arr[middle] > num) {
                right = middle - 1;
            } else if (arr[middle] < num){
                left = middle + 1;
            } else {
                return middle;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4};

        int index = binarySearch(arr, 5);

        System.out.println(index);

    }

}
